from rtmidi.midiutil import open_midiinput
import sys
import time
import json
import requests

headers = {'Content-Type': 'application/json'}

JSONdata = {}
notesSet = set()


def midiin_callback(event, data=None):
    message, deltatime = event  # message包含[channel, note, velocity]
    print("[%s] @%0.6f %r" % (port_name, deltatime, message))
    if message[2] == 100:
        JSONdata['key'] = message[1]
        notesSet.add(message[1])
        # response = requests.post(
        #     url='http://localhost:3000/midi', json=JSONdata)


try:
    midiin, port_name = open_midiinput(0)  # port=0
    print('midi port(0)!')
except (EOFError, KeyboardInterrupt):
    sys.exit()

# Attaching MIDI input callback handler.
midiin.set_callback(midiin_callback)

try:
    while True:
        if len(notesSet):
            time.sleep(0.03)
            print(notesSet)
            JSONdata['key'] = list(notesSet)
            response = requests.post(
                url='http://localhost:3000/midi', json=JSONdata)
            notesSet.clear()
        pass
        # time.sleep(0.01)
except KeyboardInterrupt:
    print('')
finally:
    print("Exit.")
    midiin.close_port()
    del midiin
